package com.zyx.xml.dom4j;

import cn.hutool.core.io.resource.ClassPathResource;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Description:
 * <br/>11.3.1 验证XML文档
 *
 * @author Yaxi.Zhang
 * @since 2022/9/25 16:06
 */
public class Dom4jValidate {
    public static void main(String[] args) throws Exception {
        // 创建启用DTD验证功能的SAXReader对象
        SAXReader reader = new SAXReader(true);
        // 启用XML Schema验证XML文档的有效性
        reader.setFeature("http://apache.org/xml/features/validation/schema"
                , true);
        // 为XML文档的设置校验有效性的Schema文档
        reader.setProperty(
                "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"
                , "book.xsd"
        );
        //为SAXReader设置ErrorHandler
        reader.setErrorHandler(new DefaultHandler() {
            public void error(SAXParseException exception)
                    throws SAXException {
                System.out.println("---error方法---");
                System.out.println(exception.getSystemId() + "文档的第"
                        + exception.getLineNumber()
                        + "行，第" + exception.getColumnNumber()
                        + "发生有效性错误，错误信息是：" + exception.getMessage());
            }
        });
        Document doc = reader.read(new ClassPathResource("ch11_03/book.xml").getFile());
    }
}
